package database;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ConnectionDialog extends JDialog {

  protected JTextField useridField;

  protected JTextField passwordField;

  protected JTextField urlField;

  protected boolean canceled;

  protected Connection connect;

  public ConnectionDialog(JFrame f) {
    super(f, "Connect To Database", true);
    buildDialogLayout();
    setSize(300, 200);
  }

  public Connection getConnection() {
    setVisible(true);
    return connect;
  }

  protected void buildDialogLayout() {
    Container pane = getContentPane();
    pane.add(new JLabel("Userid:"));
    pane.add(new JLabel("Password:"));
    pane.add(new JLabel("URL:"));

    useridField = new JTextField(10);
    pane.add(useridField);

    passwordField = new JTextField(10);
    pane.add(passwordField);

    urlField = new JTextField(15);
    pane.add(urlField);

    pane.add(getButtonPanel());
  }

  protected JPanel getButtonPanel() {
    JPanel panel = new JPanel();
    JButton btn = new JButton("Ok");
    btn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        onDialogOk();
      }
    });
    panel.add(btn);
    return panel;
  }

  protected void onDialogOk() {
    if (attemptConnection()) {
      setVisible(false);
    }
  }

  protected boolean attemptConnection() {
    try {
      connect = DriverManager.getConnection("jdbc:sqlite:test.db");
      return true;
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, "Error connecting to " + "database: " + e.getMessage());
    }
    return false;
  }

}